package com.light.mytext.utiles;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;


import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ToolUtils {
    public static final int DEFAULT_OTHER_DRAWABLE_WIDTH = 50;
    public static final int DEFAULT_OTHER_DRAWABLE_HEIGHT = 50;

    public static int dp2px(Context context, int dp) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public static int px2dp(Context context, int px) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static boolean isMobileNO(String mobiles) {

        // ^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$
        Pattern p = Pattern
                .compile("^((\\d{7,8})|(0\\d{2,3}-\\d{7,8})|(1[34578]\\d{9}))$");
        Matcher m = p.matcher(mobiles);

        return m.matches();
    }


    /**
     * ���ַ�������ת��Ϊ������
     */
    public static int timeToHm(String str) {
        int time_hm = 0;
        try {
            Scanner input = new Scanner(str);//473316:47:47
            String s = input.next();
            int index1 = s.indexOf(":");
            int index2 = s.indexOf(":", index1 + 1);
            int hh = Integer.parseInt(s.substring(0, index1));//473316
            int mi = Integer.parseInt(s.substring(index1 + 1, index2));//47
            int ss = Integer.parseInt(s.substring(index2 + 1));//47
            System.out.println(hh * 3600000 + mi * 60000 + ss * 1000);
            time_hm = hh * 3600000 + mi * 60000 + ss * 1000;
            time_hm--;
        } catch (Exception e) {// 224403000
            // TODO: handle exception
        }
        return time_hm;

    }

    public static String HmToTime(long str) {
        String time = "";
        try {
            long hour = str / (60 * 60 * 1000);
            long minute = (str - hour * 60 * 60 * 1000) / (60 * 1000);
            long second = (str - hour * 60 * 60 * 1000 - minute * 60 * 1000) / 1000;
            if (second >= 60) {
                second = second % 60;
                minute += second / 60;
            }
            if (minute >= 60) {
                minute = minute % 60;
                hour += minute / 60;
            }
            String sh = "";
            String sm = "";
            String ss = "";
            if (hour < 10) {
                sh = "0" + String.valueOf(hour);
            } else {
                sh = String.valueOf(hour);
            }
            if (minute < 10) {
                sm = "0" + String.valueOf(minute);
            } else {
                sm = String.valueOf(minute);
            }
            if (second < 10) {
                ss = "0" + String.valueOf(second);
            } else {
                ss = String.valueOf(second);
            }
            System.out.println(sh + sm + ss);
            System.out.println(hour + "a" + minute + "a" + second + "a");
            time = hour + ":" + minute + ":" + second;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return time;

    }

    /**
     * �����ֻ��ķֱ��ʴ� dp �ĵ�λ ת��Ϊ px(����)
     */
    public static int dip2px(Context context, double dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    /**
     * 是否是邮箱
     */
    public static boolean isEmail(String strEmail) {
        // String strPattern =
        // "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        String strPattern = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";

        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(strEmail);
        return m.matches();
    }

    //把对象转化成Json类型的字符串
    /*public static String getJson(Object object) {
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("list", object);
        String myjson = JSON.toJSONString(hashMap);
        return myjson;
    }*/


    /**
     * 获取当前时间
     */
    public static String getNowTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }

    /**
     * Android 音乐播放器应用里，读出的音乐时长为 long 类型以毫秒数为单位，例如：将 234736 转化为分钟和秒应为 03:55 （包含四舍五入）
     *
     * @param duration 音乐时长
     * @return
     */
    public static String timeParse(long duration) {
        String time = "";
        long minute = duration / 60000;
        long seconds = duration % 60000;
        long second = Math.round((float) seconds / 1000);
        if (minute < 10) {
            time += "0";
        }
        time += minute + ":";
        if (second < 10) {
            time += "0";
        }
        time += second;
        return time;
    }

    /**
     * java 把秒转化为00:00:00格式
     *
     * @param timeTemp
     * @return
     */
    public static String formatTime(Object timeTemp) {
        int timeParam = 0;
        if (timeTemp instanceof Integer) {
            timeParam = (Integer) timeTemp;
        }
        if (timeTemp instanceof String) {
            timeParam = Integer.valueOf((String) timeTemp);
        }

        int second = timeParam % 60;
        int minuteTemp = timeParam / 60;
        if (minuteTemp > 0) {
            int minute = minuteTemp % 60;
            int hour = minuteTemp / 60;
            if (hour > 0) {
                return (hour > 10 ? (hour + "") : ("0" + hour)) + ":" + (minute > 10 ? (minute + "") : ("0" + minute))
                        + ":" + (second >= 10 ? (second + "") : ("0" + second));
            } else {
                return "00:" + (minute > 10 ? (minute + "") : ("0" + minute)) + ":"
                        + (second >= 10 ? (second + "") : ("0" + second));
            }
        } else {
            return "00:00:" + (second >= 10 ? (second + "") : ("0" + second));
        }
    }


    //截取头像链接后的VIP标识
    public static String getVipData(String url) {
        String str_url = "";
        if (!TextUtils.isEmpty(url) && url.contains("?")) {
            Log.i("BaoHan", url + "is" + url.contains("?"));
            str_url = url.substring(url.lastIndexOf("?") + 1, url.lastIndexOf("&"));
        }
        return str_url;
    }

    //截取头像链接后的VIP标识
    public static String getRenZhengData(String url) {
        String str_url = "";
        if (!TextUtils.isEmpty(url) && url.contains("&")) {
            str_url = url.substring(url.lastIndexOf("&") + 1);
        }
        return str_url;
    }


    public static int getResId(String variableName, Class<?> c) {
        try {
            Field idField = c.getDeclaredField(variableName);
            return idField.getInt(idField);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }


    /**
     * 禁止EditText输入特殊字符
     *
     * @param editText
     */
    public static void setEditTextInhibitInputSpeChat(EditText editText) {

        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String speChat = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if (matcher.find()) return "";
                else return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "1.0.1";
        }
    }

    /**
     * 获取软件版本号
     */
    public static int getVerCode(Context context) {
        int verCode = -1;
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            verCode = info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return verCode;
    }

    /**
     * 日期转换为毫秒
     *
     * @param data
     * @return
     */
    public static long getDataToLong(String data) {
        long dateToSecond = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");//要转换的日期格式，根据实际调整""里面内容
        try {
            dateToSecond = sdf.parse(data).getTime();//sdf.parse()实现日期转换为Date格式，然后getTime()转换为毫秒数值
            System.out.print(dateToSecond);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateToSecond;
    }

    /**
     *
     */
    public static String LongToString(Long datalong) {
        Date dat = new Date(datalong);
        GregorianCalendar gc = new GregorianCalendar(); //标准阳历
        gc.setTime(dat); //利用setTime()设置其时间
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm");
        String sb = sdf.format(gc.getTime()); //利用format()将日期类型转换为String类型。
        System.out.println(sb);
        return sb;
    }

    /**
     * 取得当月天数
     */
    public static int getCurrentMonthLastDay() {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.DATE, 1);//把日期设置为当月第一天
        a.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }

    /**
     * 判断日期是否过期
     *
     * @param datatime
     * @return
     */
    public static boolean Ispassed(String datatime) {
        if (datatime.isEmpty()) {
            return false;
        }
        // 当前的时刻
        Calendar pre = Calendar.getInstance();
        Date predate = new Date(System.currentTimeMillis());
        pre.setTime(predate);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long millionSeconds = 0;//毫秒bai
        try {
            millionSeconds = sdf.parse(datatime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 设定的时刻
        Calendar cal = Calendar.getInstance();
        Date date = new Date(millionSeconds);
        cal.setTime(date);


        if (cal.get(Calendar.YEAR) == (pre.get(Calendar.YEAR))) {
            int diffDay = cal.get(Calendar.DAY_OF_YEAR) - pre.get(Calendar.DAY_OF_YEAR);
            int diffHour = cal.get(Calendar.HOUR_OF_DAY) - pre.get(Calendar.HOUR_OF_DAY);
            int diffMin = cal.get(Calendar.MINUTE) - pre.get(Calendar.MINUTE);
            if (diffDay == 0) {
                if (diffHour == 0) {
                    if (diffMin >= 0) {
                        return false;
                    }
                } else if (diffHour > 0) {
                    return false;
                }
            } else if (diffDay > 0) {
                return false;
            }
        } else if (cal.get(Calendar.YEAR) > (pre.get(Calendar.YEAR))) {
            return false;
        }
        return true;
    }

    /**
     * 从Drawable中获取Bitmap对象
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawable2Bitmap(Drawable drawable) {
        try {
            if (drawable == null) {
                return null;
            }

            if (drawable instanceof BitmapDrawable) {
                return ((BitmapDrawable) drawable).getBitmap();
            }

            int intrinsicWidth = drawable.getIntrinsicWidth();
            int intrinsicHeight = drawable.getIntrinsicHeight();
            Bitmap bitmap = Bitmap.createBitmap(
                    intrinsicWidth <= 0 ? DEFAULT_OTHER_DRAWABLE_WIDTH
                            : intrinsicWidth,
                    intrinsicHeight <= 0 ? DEFAULT_OTHER_DRAWABLE_HEIGHT
                            : intrinsicHeight, Bitmap.Config.ARGB_8888);

            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            return bitmap;
        } catch (OutOfMemoryError e) {
            return null;
        }

    }

}
